import { Breadcrumb, Flex, Skeleton } from 'antd';
import { useEffect, useState } from 'react';
import { HomeOutlined } from '@ant-design/icons';
import { ResourceApi } from '@/api/resource/api.js';
import { useNavigate } from 'react-router-dom';

/**
 * 目录面包屑
 *
 * @param props {Object} 属性
 * @param props.pId {Number} 父级目录ID
 */
export default function DirBreadcrumb(props) {
  const { pId } = props;
  // 面包屑
  const [breadcrumb, setBreadcrumb] = useState([]);
  // 加载
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    getBreadcrumb();
  }, [pId]);

  // 获取面包屑
  function getBreadcrumb() {
    let breadcrumb = [];
    // 根目录
    const root = {
      href: '#pId=0',
      title: (
        <Flex gap={4}>
          <HomeOutlined />
          根目录
        </Flex>
      )
    };
    if (pId === 0 || pId === null) {
      delete root.href;
    }
    breadcrumb.push(root);
    setLoading(true);
    // 动态加载面包屑
    ResourceApi.getBreadcrumb(pId)
      .then(({ code, data }) => {
        if (code === 0) {
          breadcrumb.push(
            ...data
              .map((item) => {
                let json;
                if (Number(pId) !== item.resourceId) {
                  json = {
                    href: `#pId=${item.resourceId}`,
                    title: <span>{item.resourceName}</span>
                  };
                } else {
                  json = { title: <span>{item.resourceName}</span> };
                }
                return json;
              })
              // 数组倒排
              .reverse()
          );
        }
        setBreadcrumb(breadcrumb);
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
      });
  }

  if (loading) {
    return (
      <Skeleton.Node active style={{ height: 22, width: 600, marginBottom: 'var(--ant-margin)' }} />
    );
  }

  return <Breadcrumb style={{ marginBottom: 'var(--ant-margin)' }} items={breadcrumb} />;
}
